package luren.king.wechatlite.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import luren.king.wechatlite.pojo.Message;

public class MessageHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "messages.db";
    private static final int DATABASE_VERSION = 1;

    public static final String TABLE_MESSAGES = "messages";
    public static final String COLUMN_EMAIL = "email";
    public static final String COLUMN_MESSAGE = "message";
    public static final String COLUMN_AVATAR = "avatar";
    public static final String COLUMN_NAME = "name";

    private static final String TABLE_CREATE =
            "CREATE TABLE " + TABLE_MESSAGES + " (" +
                    COLUMN_EMAIL + " TEXT PRIMARY KEY, " +
                    COLUMN_MESSAGE + " TEXT, " +
                    COLUMN_AVATAR + " TEXT, " +
                    COLUMN_NAME + " TEXT);";

    public MessageHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(TABLE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_MESSAGES);
        onCreate(db);
    }

    public void addOrUpdateMessage(Message message) {
        SQLiteDatabase db = this.getWritableDatabase();
        if (isEmailExists(db, message.getEmail())) {
            updateMessage(db, message);
        } else {
            addMessage(db, message);
        }
        db.close();
    }

    private boolean isEmailExists(SQLiteDatabase db, String email) {
        Cursor cursor = db.query(
                TABLE_MESSAGES,
                new String[]{COLUMN_EMAIL},
                COLUMN_EMAIL + " = ?",
                new String[]{email},
                null,
                null,
                null
        );

        boolean exists = (cursor.getCount() > 0);
        cursor.close();
        return exists;
    }

    private void addMessage(SQLiteDatabase db, Message message) {
        ContentValues values = new ContentValues();
        values.put(COLUMN_EMAIL, message.getEmail());
        values.put(COLUMN_MESSAGE, message.getMessage());
//        values.put(COLUMN_AVATAR, message.getAvatar());
        values.put(COLUMN_NAME, message.getName());

        db.insert(TABLE_MESSAGES, null, values);
    }

    private void updateMessage(SQLiteDatabase db, Message message) {
        ContentValues values = new ContentValues();
        values.put(COLUMN_MESSAGE, message.getMessage());
//        values.put(COLUMN_AVATAR, message.getAvatar());
        values.put(COLUMN_NAME, message.getName());

        db.update(
                TABLE_MESSAGES,
                values,
                COLUMN_EMAIL + " = ?",
                new String[]{message.getEmail()}
        );
    }

    public void deleteMessage(String email) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_MESSAGES, COLUMN_EMAIL + " = ?", new String[]{email});
        db.close();
    }

    public List<Message> getAllMessages() {
        List<Message> messages = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_MESSAGES, null, null, null, null, null, null);

        if (cursor.moveToFirst()) {
            do {
//                Message message = new Message(
//                        cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_EMAIL)),
//                        cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_MESSAGE)),
//                        cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_AVATAR)),
//                        cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_NAME))
//                );
                Message message = new Message();
                message.setEmail(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_EMAIL)));
                message.setMessage(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_MESSAGE)));
                message.setName(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_EMAIL)));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    message.setTime(LocalDateTime.now().toString());
                }
                messages.add(message);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return messages;
    }
}
